// Global variables for gallery
let db = null;
let allIcons = [];
let categories = [];
let styles = [];

// Configuration
let config = {
    apiKey: localStorage.getItem('deepseek_api_key') || '',
    simulationMode: localStorage.getItem('simulation_mode') === 'true'
};

// 分页配置
let paginationConfig = {
    itemsPerPage: 24, // 默认每页24个项目
    currentPage: 1
};

// Initialize the gallery
document.addEventListener('DOMContentLoaded', function() {
    // Gallery elements
    const importDbBtn = document.getElementById('import-db-btn');
    const dbFileInput = document.getElementById('db-file-input');
    const categoryFilter = document.getElementById('category-filter');
    const styleFilter = document.getElementById('style-filter');
    const searchInput = document.getElementById('search-input');
    const galleryContainer = document.getElementById('gallery-container');
    const itemsPerPageSelect = document.getElementById('items-per-page');
    // 分页控件元素
    const firstPageBtn = document.getElementById('first-page');
    const prevPageBtn = document.getElementById('prev-page');
    const nextPageBtn = document.getElementById('next-page');
    const lastPageBtn = document.getElementById('last-page');
    const pageInfo = document.getElementById('page-info');
    const paginationControls = document.getElementById('pagination-controls');
    const statusBar = document.getElementById('status-bar');
    const settingsBtn = document.getElementById('settings-btn');
    const settingsDialog = document.getElementById('settings-dialog');
    const saveSettingsBtn = document.getElementById('save-settings');
    const cancelSettingsBtn = document.getElementById('cancel-settings');
    const apiKeyInput = document.getElementById('api-key');
    const simulationModeCheckbox = document.getElementById('simulation-mode');

    // Settings dialog handlers

    importDbBtn.addEventListener('click', () => {
        dbFileInput.click();
    });

    dbFileInput.addEventListener('change', handleDbFileSelect);
    categoryFilter.addEventListener('change', loadGalleryItems);
    styleFilter.addEventListener('change', loadGalleryItems);
    searchInput.addEventListener('input', loadGalleryItems);
    itemsPerPageSelect.addEventListener('change', handleItemsPerPageChange);
    
    // 添加分页按钮事件监听器
    firstPageBtn.addEventListener('click', goToFirstPage);
    prevPageBtn.addEventListener('click', goToPrevPage);
    nextPageBtn.addEventListener('click', goToNextPage);
    lastPageBtn.addEventListener('click', goToLastPage);

    // Initialize SQL.js
    initSqlJs({
        locateFile: file => `https://cdn.jsdelivr.net/npm/sql.js@1.8.0/dist/${file}`
    }).then(SQL => {
        console.log('SQL.js initialized');
        
        // 不再尝试从缓存加载，直接提示用户导入数据库
        updateStatus('请点击"导入数据库"按钮加载数据库文件');
        hidePaginationControls();
        galleryContainer.innerHTML = '<p class="no-data">请导入数据库文件</p>';

        // Function to load local db file via file input
        function loadLocalDbFile(SQL) {
            console.log('Waiting for user to select database file');
            updateStatus('请点击"导入数据库"按钮加载数据库文件');
        }
    });

    // Handle database file selection
    function handleDbFileSelect(event) {
        const file = event.target.files[0];
        if (!file) return;

        const reader = new FileReader();
        reader.onload = function(e) {
            const arrayBuffer = e.target.result;
            initSqlJs({
                locateFile: file => `https://cdn.jsdelivr.net/npm/sql.js@1.8.0/dist/${file}`
            }).then(SQL => {
                try {
                    db = new SQL.Database(new Uint8Array(arrayBuffer));
                    console.log('Database loaded successfully');

                    // 不再缓存数据库，直接加载
                    loadCategories();
                    loadGalleryItems();
                    updateStatus('数据库导入成功');
                } catch (error) {
                    console.error('Failed to load database:', error);
                    updateStatus('数据库导入失败');
                    alert('导入数据库失败: ' + error.message);
                }
            });
        };
        reader.readAsArrayBuffer(file);

        // Reset file input to allow selecting the same file again
        dbFileInput.value = '';
    }

    // Load categories from database
    function loadCategories() {
        if (!db) return;

        try {
            // Load categories
            const categoryStmt = db.prepare('SELECT id, name FROM categories ORDER BY id');
            const categoriesResult = [];
            while (categoryStmt.step()) {
                const row = categoryStmt.getAsObject();
                categoriesResult.push({id: row.id, name: row.name});
            }
            categoryStmt.free();

            // Clear existing options except 'all'
            while (categoryFilter.options.length > 1) {
                categoryFilter.remove(1);
            }

            // Add new categories
            categoriesResult.forEach(category => {
                if (!categories.find(c => c.id === category.id)) {
                    categories.push(category);
                }
                const option = document.createElement('option');
                option.value = category.id;
                option.textContent = category.name;
                categoryFilter.appendChild(option);
            });

            // Load styles
            const styleStmt = db.prepare('SELECT DISTINCT style FROM svg_icons ORDER BY style');
            const stylesResult = [];
            while (styleStmt.step()) {
                const row = styleStmt.getAsObject();
                stylesResult.push(row.style);
            }
            styleStmt.free();

            // Clear existing options except 'all'
            while (styleFilter.options.length > 1) {
                styleFilter.remove(1);
            }

            // Add new styles
            stylesResult.forEach(style => {
                if (!styles.includes(style)) {
                    styles.push(style);
                }
                const option = document.createElement('option');
                option.value = style;
                option.textContent = style;
                styleFilter.appendChild(option);
            });
        } catch (error) {
            console.error('Failed to load categories and styles:', error);
        }
    }

    // Load gallery items based on filters
    function loadGalleryItems() {
        if (!db) {
            galleryContainer.innerHTML = '<p class="no-data">请先导入数据库</p>';
            hidePaginationControls();
            return;
        }

        try {
            const selectedCategory = categoryFilter.value;
            const selectedStyle = styleFilter.value;
            const searchTerm = searchInput.value.toLowerCase().trim();

            let query = 'SELECT i.*, c.name as category_name FROM svg_icons i JOIN categories c ON i.category_id = c.id WHERE 1=1';
            const params = [];

            if (selectedCategory !== 'all') {
                query += ' AND i.category_id = ?';
                params.push(selectedCategory);
            }

            if (selectedStyle !== 'all') {
                query += ' AND i.style = ?';
                params.push(selectedStyle);
            }

            if (searchTerm) {
                query += ' AND (i.name LIKE ? OR i.ai_prompt LIKE ?)';
                params.push(`%${searchTerm}%`, `%${searchTerm}%`);
            }

            query += ' ORDER BY i.name';

            const stmt = db.prepare(query);
            stmt.bind(params);

            allIcons = [];
            while (stmt.step()) {
                allIcons.push(stmt.getAsObject());
            }
            stmt.free();

            // 更新每页显示数量
            paginationConfig.itemsPerPage = parseInt(itemsPerPageSelect.value);
            // 重置到第一页
            paginationConfig.currentPage = 1;
            
            renderGalleryItems(allIcons);
            updatePaginationControls();
        } catch (error) {
            console.error('Failed to load gallery items:', error);
            galleryContainer.innerHTML = `<p class="error">加载图标失败: ${error.message}</p>`;
            hidePaginationControls();
        }
    }

    // 处理每页显示数量变化
    function handleItemsPerPageChange() {
        paginationConfig.itemsPerPage = parseInt(this.value);
        paginationConfig.currentPage = 1; // 重置到第一页
        renderGalleryItems(allIcons);
        updatePaginationControls();
    }

    // 渲染图库项目
    function renderGalleryItems(icons) {
        galleryContainer.innerHTML = '';

        if (icons.length === 0) {
            galleryContainer.innerHTML = '<p class="no-data">没有找到匹配的图标</p>';
            hidePaginationControls();
            return;
        }

        // 计算当前页应该显示的图标
        const startIndex = (paginationConfig.currentPage - 1) * paginationConfig.itemsPerPage;
        const endIndex = Math.min(startIndex + paginationConfig.itemsPerPage, icons.length);
        const iconsToShow = icons.slice(startIndex, endIndex);

        iconsToShow.forEach(icon => {
            const galleryItem = document.createElement('div');
            galleryItem.className = 'gallery-item';

            // SVG container
            const svgContainer = document.createElement('div');
            svgContainer.innerHTML = icon.svg_content;
            galleryItem.appendChild(svgContainer);

            // Icon name
            const nameElement = document.createElement('div');
            nameElement.className = 'gallery-item-name';
            nameElement.textContent = icon.name;
            galleryItem.appendChild(nameElement);

            // Actions
            const actionsElement = document.createElement('div');
            actionsElement.className = 'gallery-item-actions';

            // Save button only
            const saveBtn = document.createElement('button');
            saveBtn.textContent = '保存';
            saveBtn.addEventListener('click', () => saveSvg(icon.svg_content, icon.id));
            actionsElement.appendChild(saveBtn);

            galleryItem.appendChild(actionsElement);
            galleryContainer.appendChild(galleryItem);
        });

        // 如果只有一页，则隐藏分页控件
        if (icons.length <= paginationConfig.itemsPerPage) {
            hidePaginationControls();
        } else {
            showPaginationControls();
        }
    }

    // 更新分页控件
    function updatePaginationControls() {
        if (allIcons.length === 0) {
            hidePaginationControls();
            return;
        }

        const totalPages = Math.ceil(allIcons.length / paginationConfig.itemsPerPage);
        
        // 更新页面信息
        pageInfo.textContent = `${paginationConfig.currentPage} / ${totalPages}`;
        
        // 更新按钮状态
        firstPageBtn.disabled = paginationConfig.currentPage === 1;
        prevPageBtn.disabled = paginationConfig.currentPage === 1;
        nextPageBtn.disabled = paginationConfig.currentPage === totalPages;
        lastPageBtn.disabled = paginationConfig.currentPage === totalPages;
        
        showPaginationControls();
    }

    // 显示分页控件
    function showPaginationControls() {
        paginationControls.style.display = 'flex';
    }

    // 隐藏分页控件
    function hidePaginationControls() {
        paginationControls.style.display = 'none';
    }

    // 首页
    function goToFirstPage() {
        paginationConfig.currentPage = 1;
        renderGalleryItems(allIcons);
        updatePaginationControls();
    }

    // 上一页
    function goToPrevPage() {
        if (paginationConfig.currentPage > 1) {
            paginationConfig.currentPage--;
            renderGalleryItems(allIcons);
            updatePaginationControls();
        }
    }

    // 下一页
    function goToNextPage() {
        const totalPages = Math.ceil(allIcons.length / paginationConfig.itemsPerPage);
        if (paginationConfig.currentPage < totalPages) {
            paginationConfig.currentPage++;
            renderGalleryItems(allIcons);
            updatePaginationControls();
        }
    }

    // 末页
    function goToLastPage() {
        const totalPages = Math.ceil(allIcons.length / paginationConfig.itemsPerPage);
        paginationConfig.currentPage = totalPages;
        renderGalleryItems(allIcons);
        updatePaginationControls();
    }

    // View icon in a larger dialog
    function viewIcon(icon) {
        // Create a simple alert with the SVG code
        // In a real application, you might want to create a nicer preview dialog
        alert(`图标名称: ${icon.name}\n\nSVG 代码:\n${icon.svg_content}`);
    }

    // Save SVG to file
    function saveSvg(svg, index) {
        showFormatDialog(svg, index);
    }

    // Show format selection dialog
    function showFormatDialog(svg, index) {
        // Create dialog overlay
        const overlay = document.createElement('div');
        overlay.className = 'dialog-overlay';
        overlay.style.cssText = `
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.5);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 1000;
        `;

        // Create dialog content
        const dialog = document.createElement('div');
        dialog.className = 'format-dialog';
        dialog.style.cssText = `
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.3);
            text-align: center;
            min-width: 300px;
        `;

        dialog.innerHTML = `
            <h3 style="margin-bottom: 20px;">选择保存格式</h3>
            <div style="display: flex; gap: 15px; justify-content: center; margin-bottom: 20px;">
                <button class="format-btn" data-format="svg" style="padding: 10px 20px; border: 1px solid #ddd; border-radius: 6px; background: #f8f9fa; cursor: pointer;">
                    <div style="font-size: 24px; margin-bottom: 5px;">🖼️</div>
                    <div>SVG</div>
                </button>
                <button class="format-btn" data-format="png" style="padding: 10px 20px; border: 1px solid #ddd; border-radius: 6px; background: #f8f9fa; cursor: pointer;">
                    <div style="font-size: 24px; margin-bottom: 5px;">🖼️</div>
                    <div>PNG</div>
                </button>
            </div>
            <button id="cancel-format" style="padding: 8px 16px; border: 1px solid #ddd; border-radius: 4px; background: #f8f9fa; cursor: pointer;">取消</button>
        `;

        overlay.appendChild(dialog);
        document.body.appendChild(overlay);

        // Add event listeners
        dialog.querySelectorAll('.format-btn').forEach(btn => {
            btn.addEventListener('click', (e) => {
                const format = e.currentTarget.dataset.format;
                overlay.remove();
                if (format === 'svg') {
                    downloadSvg(svg, index);
                } else if (format === 'png') {
                    convertToPng(svg, index);
                }
            });
        });

        dialog.querySelector('#cancel-format').addEventListener('click', () => {
            overlay.remove();
        });
    }

    // Download SVG file
    function downloadSvg(svg, index) {
        // Create a blob with SVG content
        const blob = new Blob([svg], {type: 'image/svg+xml'});
        const url = URL.createObjectURL(blob);

        // Create download link
        const a = document.createElement('a');
        a.href = url;
        a.download = `svg-icon-${index + 1}.svg`;
        document.body.appendChild(a);
        a.click();

        // Clean up
        document.body.removeChild(a);
        URL.revokeObjectURL(url);

        updateStatus('SVG图标已保存');
    }

    // Convert SVG to PNG and download
    function convertToPng(svg, index) {
        updateStatus('正在转换为PNG...');

        // Create a temporary SVG element
        const parser = new DOMParser();
        const svgDoc = parser.parseFromString(svg, 'image/svg+xml');
        const svgElement = svgDoc.documentElement;

        // Get SVG dimensions
        const width = svgElement.getAttribute('width') || svgElement.getAttribute('viewBox')?.split(' ')[2] || 512;
        const height = svgElement.getAttribute('height') || svgElement.getAttribute('viewBox')?.split(' ')[3] || 512;

        // Create canvas for conversion
        const canvas = document.createElement('canvas');
        canvas.width = parseInt(width);
        canvas.height = parseInt(height);
        const ctx = canvas.getContext('2d');

        // Create image from SVG
        const img = new Image();
        const svgBlob = new Blob([svg], {type: 'image/svg+xml'});
        const url = URL.createObjectURL(svgBlob);

        img.onload = function() {
            // Draw image to canvas
            ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
            
            // Convert to PNG and download
            canvas.toBlob(function(blob) {
                const pngUrl = URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = pngUrl;
                a.download = `svg-icon-${index + 1}.png`;
                document.body.appendChild(a);
                a.click();

                // Clean up
                document.body.removeChild(a);
                URL.revokeObjectURL(url);
                URL.revokeObjectURL(pngUrl);

                updateStatus('PNG图标已保存');
            }, 'image/png');
        };

        img.onerror = function() {
            updateStatus('PNG转换失败');
            URL.revokeObjectURL(url);
        };

        img.src = url;
    }

    // Function to update status bar
    function updateStatus(message) {
        const statusBar = document.getElementById('status-bar');
        statusBar.textContent = message;
        
        // Optional: Highlight the status message temporarily
        statusBar.style.backgroundColor = '#e8f5e9';
        setTimeout(() => {
            statusBar.style.backgroundColor = '';
        }, 2000);
    }
});